package com.onix.scalecamerapreview.translate.OCR;

import android.util.Log;

import com.google.gson.Gson;
import com.onix.scalecamerapreview.translate.RetrofitUtil;

import java.util.List;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MsWordRecognition {
    public static String URL = "https://westus.api.cognitive.microsoft.com/vision/v2.0/ocr";

    public void excute(byte[] content){
        RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"),content);

        MultipartBody.Builder multiBuilder=new MultipartBody.Builder();
        multiBuilder.addPart(body);
        multiBuilder.addFormDataPart("language","unk");
        multiBuilder.addFormDataPart("detectOrientation","true");
        RequestBody multiBody=multiBuilder.build();
        Request request = new Request.Builder()
                .url(URL)
                .post(multiBody)
                .addHeader("Content-Type", "application/octet-stream")
                .addHeader("Ocp-Apim-Subscription-Key", "de418b4320664b1598d05b39af0736c6")
                .build();
        try {
            OkHttpClient httpClient = RetrofitUtil.getHttpClient();
            if(httpClient!=null){
                Log.d("AAA","newCall: ");
                Call call = httpClient.newCall(request);
                if(call!=null){
                    Log.d("AAA","execute: ");
                    Response response= call.execute();
                    if (response.isSuccessful()){
                        String string = response.body().string();
                        Log.d("AAA","结果: "+string);
                        Gson gson = new Gson();
                        MsOcrBean msOcrBean = gson.fromJson(string, MsOcrBean.class);
                        List<MsOcrBean.RegionsBean> regions = msOcrBean.getRegions();
                        Log.d("AAA","regions "+regions.size());
                        MsOcrBean.RegionsBean regionsBean = regions.get(0);
                        List<MsOcrBean.RegionsBean.LinesBean> lines = regionsBean.getLines();
                        Log.d("AAA","lines "+lines.size());
                        for (MsOcrBean.RegionsBean.LinesBean line : lines) {
                            StringBuffer stringBuffer = new StringBuffer();
                            for (MsOcrBean.RegionsBean.LinesBean.WordsBean wordsBean : line.getWords()) {
                                stringBuffer.append(wordsBean.getText());
                            }
                            Log.d("AAA"," "+stringBuffer.toString());
                        }


                    }
                }
            }

        } catch (Exception e) {
            Log.d("AAA","e "+e);
            e.printStackTrace();
        }
    }



}
